"""
Contains the base classes for things pertaining to robot device components
"""

import re

class Component(object):
    
    """
    Base class for all HasCOMPONENT classes
    
    Makes sure we are using new-style inheritance and adds a list called dev
    to an extending object's namespace upon initialization
    Whenever a bot class extends HasCOMPONENT classes it gets a list of devices
    that it can use stored in a list called dev
    """
    
    def __init__(self):
        super(Component, self).__init__()
        self.dev = DeviceList()
        
class Device(object):
    """
    Base class of all devices
    
    Any device found in dev, that is to be used in a bot should extend this class
    """
    
    def __init__(self):
        super(Device, self).__init__()
        try:
            if not ord(self.name[-1]) in range(48, 58):
                self.name += "_"
        except AttributeError:
            self.name = "gen"
    
        
# DeviceList should logically extend/act like a dict, no? -nasser
class DeviceList(dict):
    """
    Holds device objects
    """
     
    def __init__(self):
        dict.__init__(self)
        self.__name__ = 'DeviceList' # Added so that calling help on a DeviceList object does not fail
         
    def __getattr__(self, name):
        """
        devices are retrieved as DeviceList.dev<num>, example: 
        dev = DeviceList()
        dev.install( hda() )
        dev.install( hda() )
        dev.hda1 <= first drive
        dev.hda2 <= second drive
        dev.hda <= list of all drives
        """
        # Check for a device number in name
        p = re.compile(r"\d\d*$")
        p = p.search(name)
        if p is None:
            # No number, return list of devices
            return self[name]
        
        start, end = p.span()
        
        number = int(name[start:end]) -1
        name = name[:start] # better? -nasser
        return self[name][number]
    
    # avoid misbehaving users -nasser
    def __getitem__(self, item):
        raise SyntaxError("Illegal use of device list. Use dev.devname instead.")
    
    def __setitem__(self, item, value):
        raise SyntaxError("Illegal use of device list. Use dev.devname instead.")
        
    # I dont like using __and__ to append items, it dosent feel right -nasser
    def install(self, new_device):
        """
        Devices are installed into the list
        """
        if isinstance(new_device, Device):
            if new_device.name in self :
                self[new_device.name].append(new_device)
            else:
                self[new_device.name] = [new_device]
            return self
        else:
            raise TypeError("A device should extend Device, no?")